#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>
#include "RingQueue.hpp"
#include "Task.hpp"

pthread_mutex_t _pmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t _cmutex = PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t _pcond = PTHREAD_COND_INITIALIZER;
pthread_cond_t _ccond = PTHREAD_COND_INITIALIZER;

struct ThreadData
{
    RingQueue<Task>* rq;
    std::string threadname;
};

// 生产者
void *Productor(void *args)
{
    // sleep(3);

    ThreadData* td = static_cast<ThreadData*>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name = td->threadname;
    int len = opers.size();

    while (true)
    {
        // 1.获取数据
        int data1 = rand() % 10 + 1;
        usleep(10);
        int data2 = rand() % 10;
        char op = opers[rand() % len];
        Task t(data1,data2,op);

        // 2.生产数据
        rq->Push(t);
        pthread_mutex_lock(&_pmutex);
        // 生产者无需等待，如果满了，会自动等待消费者结束
        std::cout << "Productor data done, data is : " << t.GetTask()
                  << " who: " << name
                  << std::endl;
        // 需要由生产者来唤醒消费者去消费
        pthread_mutex_unlock(&_pmutex);
        pthread_cond_signal(&_ccond);

        sleep(1);
    }
    return nullptr;
}
// 消费者
void *Consumer(void *args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name = td->threadname;

    while (true)
    {
        // 1.消费数据
        Task t;
        pthread_mutex_lock(&_cmutex);
        rq->Pop(&t);
        pthread_cond_wait(&_ccond, &_cmutex);
        // 消费者需要等待，由生产者唤醒
        // 2. 处理数据
        t();
        std::cout << "Consumer get data, data is : " << t.GetTask() 
                  << " who: " << name
                  << " resule: " << t.GetResult()
                  << std::endl;
        pthread_mutex_unlock(&_cmutex);
        // sleep(1);
    }
    return nullptr;
}
int main()
{
    srand(time(nullptr) ^ getpid());

    RingQueue<Task> *rq = new RingQueue<Task>(50);
    pthread_t c[3], p[5];

    // 创建线程
    for (int i = 0; i < 1; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Consumer-" + std::to_string(i);
        pthread_create(c + i, nullptr, Consumer, td);
    }
    for (int i = 0; i < 1; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Productor-" + std::to_string(i);
        pthread_create(p + i, nullptr, Productor, td);
    }
    
    // 等待线程结束
    for (int i = 0; i < 1; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for (int i = 0; i < 1; i++)
    {
        pthread_join(p[i], nullptr);
    }

    return 0;
}